package com.smart.community.region.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smart.community.commons.annotation.ApiLog;
import com.smart.community.commons.enums.ApiLogOperationType;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.region.dto.ResidentAddDTO;
import com.smart.community.region.entity.Resident;
import com.smart.community.region.service.IResidentHouseholdService;
import com.smart.community.region.service.IResidentService;
import com.smart.community.region.vo.ResidentHouseholdVO;
import com.smart.community.region.vo.ResidentMobileHouseholdVO;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 住户信息管理控制器
 * 
 * @author Wu.Liang
 * @since 2025-07-28
 */
@RestController
@RequestMapping("/region/resident")
@Tag(name = "住户管理", description = "住户信息管理相关接口")
@Slf4j
public class ResidentController {
	@Autowired
	private IResidentService residentService;
	@Autowired
	private IResidentHouseholdService residentHouseholdService;

	/**
	 * 获取住户列表
	 */
	@GetMapping
	@Operation(summary = "获取住户列表", description = "分页查询住户信息，支持条件过滤和数据权限控制")
	public Result<IPage<ResidentHouseholdVO>> getResidentList(
			@RequestParam(defaultValue = "1") Integer current,
			@RequestParam(defaultValue = "10") Integer size,
			@RequestParam(required = false) Long communityId,
			@RequestParam(required = false) Long buildingId,
			@RequestParam(required = false) Long unitId,
			@RequestParam(required = false) Long householdId,
			@RequestParam(required = false) String realName,
			@RequestParam(required = false) Integer residentType,
			@RequestParam(required = false) Integer status) throws Exception {
		log.info("获取住户列表，查询条件：current={}, size={}, communityId={}, buildingId={}, unitId={}, householdId={}, realName={}, residentType={}, status={}", 
				current, size, communityId, buildingId, unitId, householdId, realName, residentType, status);
		
		try {
		// 构建查询条件
		Map<String, Object> queryParams = new HashMap<>();
		if (communityId != null) {
			queryParams.put("communityId", communityId);
		}
		if (buildingId != null) {
			queryParams.put("buildingId", buildingId);
		}
		if (unitId != null) {
			queryParams.put("unitId", unitId);
		}
		if (householdId != null) {
			queryParams.put("householdId", householdId);
		}
		if (realName != null && !realName.trim().isEmpty()) {
			queryParams.put("realName", realName.trim());
		}
		if (residentType != null) {
			queryParams.put("residentType", residentType);
		}
		if (status != null) {
			queryParams.put("status", status);
		}
			
			// 调用服务层方法进行分页查询
			IPage<ResidentHouseholdVO> result = residentHouseholdService.getResidentListWithConditions(
					queryParams, current, size);
			
			return Result.success(result);
		} catch (Exception e) {
			log.error("获取住户列表失败", e);
			return Result.error("获取住户列表失败：" + e.getMessage());
		}
	}

	/**
	 * 新增住户信息
	 */
	@ApiLog(logTitle = "新增住户信息", logType = 2, moduleName = "区域管理", operationType = ApiLogOperationType.ADD)
	@PostMapping
	@Operation(summary = "新增住户信息", description = "新增住户基本信息和房户关联信息")
	public Result<Resident> addResident(@RequestBody ResidentAddDTO residentAddDTO) throws Exception {
		// 直接调用Service层，异常统一抛出，不捕获处理
		Resident resident = residentService.addResidentWithPermission(residentAddDTO);
		return Result.success(resident);
	}
	


	/**
	 * 更新住户信息
	 */
	@ApiLog(logTitle = "更新住户信息", logType = 2, moduleName = "区域管理", operationType = ApiLogOperationType.UPDATE)
	@PutMapping("/{id}")
	@Operation(summary = "更新住户信息", description = "更新住户基本信息")
	public Result<Void> updateResident(@PathVariable Long id, @RequestBody Resident resident) throws Exception {
			resident.setId(id);
			
			// 设置更新信息
			Long userId = SecurityUtils.getCurrentUserId();
			if (userId != null) {
				resident.setUpdateBy(userId);
			}
			
			boolean result = residentService.updateById(resident);
			if (result) {
				log.info("更新住户信息成功，住户ID：{}", id);
				return Result.success();
			} else {
				return Result.error("更新住户信息失败");
			}
	}

	/**
	 * 删除住户信息
	 */
	@ApiLog(logTitle = "删除住户信息", logType = 2, moduleName = "区域管理", operationType = ApiLogOperationType.DELETE)
	@DeleteMapping("/{id}")
	@Operation(summary = "删除住户信息", description = "删除住户基本信息")
	public Result<Void> deleteResident(@PathVariable Long id) throws Exception {
			boolean result = residentService.removeById(id);
			if (result) {
				log.info("删除住户信息成功，住户ID：{}", id);
				return Result.success();
			} else {
				return Result.error("删除住户信息失败");
			}
	}

	/**
	 * 根据用户ID获取住户信息
	 */
	@GetMapping("/user/{userId}")
	@Operation(summary = "根据用户ID获取住户信息", description = "根据用户ID查询住户信息")
	public Result<List<Resident>> getResidentsByUserId(@PathVariable Long userId) throws Exception {
		log.info("根据用户ID获取住户信息，用户ID：{}", userId);
		
		List<Resident> residents = residentService.getResidentsByUserId(userId);
		return Result.success(residents);
	}

	/**
	 * 根据姓名查询住户信息
	 */
	@GetMapping("/name/{realName}")
	@Operation(summary = "根据姓名查询住户信息", description = "根据姓名模糊查询住户信息")
	public Result<List<Resident>> getResidentsByRealName(@PathVariable String realName) throws Exception {
		log.info("根据姓名查询住户信息，姓名：{}", realName);
		
		List<Resident> residents = residentService.getResidentsByRealName(realName);
		return Result.success(residents);
	}

	/**
	 * 获取当前登录用户的房户列表（移动端报修使用）
	 */
    @GetMapping("/mobile/my-households")
    @Operation(summary = "获取当前登录用户的房户列表", description = "移动端报修时获取当前用户的房户列表，包含详细地址信息")
    public Result<List<ResidentMobileHouseholdVO>> getCurrentUserHouseholds() throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();

        log.info("获取当前登录用户的房户列表，用户ID：{}", userId);
        List<ResidentMobileHouseholdVO> list = residentHouseholdService.listMobileHouseholdsByUserId(userId);
        if (list == null || list.isEmpty()) {
            return Result.success("用户暂无关联房户", java.util.Collections.emptyList());
        }
        return Result.success("查询成功", list);
    }
}